package com.promotores;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.promotores.jsonparsing.JSONReader;
import com.promotores.jsonparsing.JSONParser;
import com.promotores.jsonparsing.JSONReader2;
import com.promotores.jsonparsing.JSONReaderListener;
import com.promotores.util.Parametros;

public class JsonEvento {
	//se llamarían todas los eventos que tengan como valor updated vacío
	public void write(List<BeanEvento> listaEventos) throws IOException, JSONException{
		for (int i=0; i<listaEventos.size(); i++){
			JSONObject obj = new JSONObject();
			Date fecha = new Date();
			java.sql.Date fechaSQL = new java.sql.Date(fecha.getTime());
			obj.put("idEvento", listaEventos.get(i).getId());
			obj.put("estado", listaEventos.get(i).getEstado());
			obj.put("updated_at", fechaSQL);
			//por terminar
			FileWriter file = new FileWriter("c:\\test.json");
			file.write(obj.toString());
		}
	}
	
	// url to make request
	private static String url = "http://200.16.7.112:3000/promoter_management/promotions/events_for_promoters/";
			
	// JSON Node names
	private static final String TAG_EVENT = "event";
	private static final String TAG_CREATED_AT = "created_at";
	private static final String TAG_UPDATED_AT = "updated_at";
	private static final String TAG_EVENT_STATE = "event_state_id";
	private static final String TAG_ID = "id";
	private static final String TAG_NOMBRE = "nombre";	
	private static final String TAG_FECHA_FIN_VENTA = "fecha_fin_venta";
	private static final String TAG_FECHA_INICIO_VENTA = "fecha_inicio_venta";
	private static final String TAG_EVENT_TYPE = "event_type";
	private static final String TAG_ID_PARENT_TYPE = "id_parent_type";
	private static final String TAG_ID_SUBTYPE = "id";
	
	private static final String TAG_ZONE = "zones";
	private static final String TAG_ZONE_NAME = "nombre";
	private static final String TAG_ZONE_DESCRIPCION = "descripcion";
	private static final String TAG_ZONE_AFORO = "aforo";
	private static final String TAG_ZONE_FARE = "fare";
	
	private static final String TAG_PROMOTOR = "promoter";
	private static final String TAG_PROMOTOR_NOMBRE ="nombre";
	private static final String TAG_PROMOTOR_APPAT = "ape_paterno";
	private static final String TAG_PROMOTOR_APMAT = "ape_materno";
	private static final String TAG_PROMOTOR_EMAIL = "email";
	
	private static final String TAG_VENUE = "venue";
	private static final String TAG_VENUE_NAME = "nombre";
	
	private static final String TAG_URL ="imagen_publicitaria_url";
	
	// contacts JSONArray
	JSONArray eventos = null;
	
	public List<BeanEvento> read(Context context){
		List<BeanEvento> lstEventos = new ArrayList<BeanEvento>();
				
		// Creating JSON Parser instance
		//JSONParser jParser = new JSONParser();
		String last_upd = Parametros.getLast_update();
		//String readValues = jParser.read(url+last_upd+"(yyyy-MM-dd'T'HH:mm:ss'Z').json");
		//System.out.println("Json0: "+readValues);
		
		JSONReader2 jReader = new JSONReader2();
		jReader.setJSONReaderListener((JSONReaderListener)context);
		try {
			//JSONArray jsonArray = new JSONArray(readValues);
			JSONArray jsonArray =(jReader.execute(url+last_upd+"(yyyy-MM-dd'T'HH:mm:ss'Z').json")).get();
			for (int i = 0; i < jsonArray.length(); i++) {
				
				JSONObject jsonObject = jsonArray.getJSONObject(i);			
							
				// Storing each json item in variable				
				int id = jsonObject.getJSONObject(TAG_EVENT).getInt(TAG_ID);
				String event_state = jsonObject.getJSONObject(TAG_EVENT).getString(TAG_EVENT_STATE);
				String nombre = jsonObject.getJSONObject(TAG_EVENT).getString(TAG_NOMBRE);
				String created_at = jsonObject.getJSONObject(TAG_EVENT).getString(TAG_CREATED_AT);
				String updated_at = jsonObject.getJSONObject(TAG_EVENT).getString(TAG_UPDATED_AT);
				String fecha_inicio_venta = jsonObject.getJSONObject(TAG_EVENT).getString(TAG_FECHA_INICIO_VENTA);
				String fecha_fin_venta = jsonObject.getJSONObject(TAG_EVENT).getString(TAG_FECHA_FIN_VENTA);
				String url = jsonObject.getJSONObject(TAG_EVENT).getString(TAG_URL);
				int tipoevento = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_EVENT_TYPE).getInt(TAG_ID_PARENT_TYPE);
				int subtipoevento = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_EVENT_TYPE).getInt(TAG_ID_SUBTYPE);
				
				//zonas
				JSONArray jsonArrayZonas = jsonObject.getJSONObject(TAG_EVENT).getJSONArray(TAG_ZONE);
				ArrayList<BeanZona> zonas = new ArrayList<BeanZona>();
				for (int j =0; j<jsonArrayZonas.length();j++){
					int aforo = jsonArrayZonas.getJSONObject(j).getInt(TAG_ZONE_AFORO);
					double fare = jsonArrayZonas.getJSONObject(j).getDouble(TAG_ZONE_FARE);
					String nombZona = jsonArrayZonas.getJSONObject(j).getString(TAG_ZONE_NAME);
					String descZona = jsonArrayZonas.getJSONObject(j).getString(TAG_ZONE_DESCRIPCION);
					BeanZona zona = new BeanZona();
					zona.setAforo(aforo);
					zona.setFare(fare);
					zona.setNombre(nombZona); //cambiar cuando se tenga nombre
					zona.setDescripcion(descZona);
					zona.setId(j+1);
					zona.setIdevento(id);
					zona.setDeleted("0");
					zona.setSaved("1");
					zona.setCreated_at(created_at);
					zona.setUpdated_at(updated_at);
					zonas.add(zona);
				}
				String nombreAmbiente = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_VENUE).getString(TAG_VENUE_NAME);
				//promotor
//				String nombrePromotor = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getString(TAG_PROMOTOR_NOMBRE);
//				String appaterno = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getString(TAG_PROMOTOR_APPAT);
//				String apmaterno = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getString(TAG_PROMOTOR_APMAT);
//				String email = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getString(TAG_PROMOTOR_EMAIL);
//				
				String nombrePromotor = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getJSONObject("user").getString(TAG_PROMOTOR_NOMBRE);
				String appaterno = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getJSONObject("user").getString(TAG_PROMOTOR_APPAT);
				String apmaterno = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getJSONObject("user").getString(TAG_PROMOTOR_APMAT);
				String email = jsonObject.getJSONObject(TAG_EVENT).getJSONObject(TAG_PROMOTOR).getJSONObject("user").getString(TAG_PROMOTOR_EMAIL);
				
				BeanEvento evento = new BeanEvento();
				evento.setId(id);
				evento.setDescripcion(nombre);
				evento.setEstado(event_state);
				evento.setFechaIni(fecha_inicio_venta);
				evento.setFechaFin(fecha_fin_venta);
				evento.setNombre(nombre);
				evento.setNomPromotor(nombrePromotor);
				evento.setApePaterno(appaterno);
				evento.setApeMaterno(apmaterno);
				evento.setEmail(email);
				evento.setCreated_at(created_at);
				evento.setUpdated_at(updated_at);
				evento.setTipoEvento(tipoevento);
				evento.setIdSubTipoEvento(subtipoevento);
				evento.setUrlImagen(url);
				evento.setDeleted("0");
				evento.setSaved("1");
				evento.setZona(zonas);
				evento.setAmbiente(nombreAmbiente);
				lstEventos.add(evento);
			}
		} catch (Exception e) {
			System.out.println("Json: Exception");
			e.printStackTrace();
			return null;
		}
		
		return lstEventos;
	}
	
	InputStream is = null;
	String result = "";
	JSONObject jArrayResult = null;
	
	public int postData(int idEvento,int estado)throws IOException, JSONException {
        // Create a new HttpClient and Post Header
        String url2 = "http://200.16.7.112:3000/promoter_management/promotions/update_events/";
	    HttpParams myParams = new BasicHttpParams();
	    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
	    HttpConnectionParams.setSoTimeout(myParams, 10000);
	    HttpClient httpclient = new DefaultHttpClient( myParams);
	//   String json=obj.toString();

	    try {
	
	        HttpPost httppost = new HttpPost(url2.toString());
//	        httppost.setHeader("Content-type", "application/json");
//            JSONObject event = new JSONObject();
            JSONObject obj = new JSONObject();

            obj.put("event_id", idEvento);
            obj.put("nuevo_estado", estado);

//          event.put(TAG_EVENT, obj);
            System.out.println("obj:" + obj);
            StringEntity se = new StringEntity(obj.toString());
	        
	        httppost.setEntity(se);
	        httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Content-Type", "application/json");
	
	        HttpResponse httpResponse = httpclient.execute(httppost);
	        HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           
 
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	            return 0;
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	            return 0;
	        } catch (IOException e) {
	            e.printStackTrace();
	            return 0;
	        } catch (JSONException e) {
				e.printStackTrace();
				return 0;
			}
	 
	        try {
	            BufferedReader reader = new BufferedReader(new InputStreamReader(
	                    is, "iso-8859-1"), 8);
	            StringBuilder sb = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                sb.append(line + "\n");
	            }
	            is.close();
	            result = sb.toString();
	        } catch (Exception e) {
	            Log.e("Buffer Error", "Error converting result " + e.toString());
	            return 0;
	        }
	 
	        // try parse the string to a JSON object
	        try {
	        	jArrayResult = new JSONObject(result);
//	        	int id = jArrayResult.getJSONObject(TAG_EVENT_PROMOTION).getInt(TAG_ID);
//	        	System.out.println("id:" + id);
//	        	return id;
	        	return 1;
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	            return 0;
	        }
	}
	
	
	public List<BeanEvento> dameEventos(int idTipo){
		JSONArray jEvento;
		try {
			jEvento=(new JSONReader().execute("http://200.16.7.112:3000/event_management/events/dameListaEventos/"+ String.valueOf(idTipo) +".json")).get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
			return null;
		} catch (ExecutionException e1) {
			e1.printStackTrace();
			return null;
		}

		List<BeanEvento> lstTipo= new ArrayList<BeanEvento>();
		try{
			for(int i=0;i < jEvento.length();i++){
			
				BeanEvento objEvento = new BeanEvento();
				objEvento.setId(jEvento.getJSONObject(i).getInt("event_id"));
				objEvento.setTipoEvento(idTipo);
//				objEvento.setTitEvento(jEvento.getJSONObject(i).getString("nombre"));
							
//				String fInicio = jEvento.getJSONObject(i).get("fecha_inicio").toString();
//				String fFin = jEvento.getJSONObject(i).get("fecha_fin").toString();		
//				
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
//				Date dateIni = formatter.parse(fInicio);
//				Date dateFin = formatter.parse(fFin);
//				
//				formatter = new SimpleDateFormat("dd MMM yyyy");
//				
//				objEvento.setFechaEvento("Del " + formatter.format(dateIni) + " al " +formatter.format(dateFin));
//				
//				objEvento.setLugarEvento(jEvento.getJSONObject(i).getString("ambiente_nombre"));
//								
//				objEvento.setUrlImagen("http://" +jEvento.getJSONObject(i).getString("imagen_publicitaria"));
//
				lstTipo.add(objEvento);
				
			}	
			return lstTipo;
		}catch(JSONException e){
			Log.e("log_tag", "Error parsing data "+e.toString());
			return null;
		}
	}
}
